package org.example.liaoxuefeng.observer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

/**
 * @author: 默苍璃
 * @date: 2024-07-18 15:40
 */
public class AsyncStore {

    private final ExecutorService executor = Executors.newFixedThreadPool(5); // 创建一个固定大小的线程池
    private List<ProductObserver> observers = new ArrayList<>();
    private Map<String, Product> products = new HashMap<>();

    public void addObserver(ProductObserver observer) {
        this.observers.add(observer);
    }

    public void removeObserver(ProductObserver observer) {
        this.observers.remove(observer);
    }

    public void addNewProduct(String name, double price) {
        Product p = new Product(name, price);
        products.put(p.getName(), p);
        notifyObserversAsync(o -> o.onPublished(p)); // 异步通知
    }

    public void setProductPrice(String name, double price) {
        Product p = products.get(name);
        p.setPrice(price);
        notifyObserversAsync(o -> o.onPriceChanged(p)); // 异步通知
    }

    private void notifyObserversAsync(Consumer<ProductObserver> action) {
        observers.forEach(observer -> executor.submit(() -> action.accept(observer)));
    }

    public void shutdown() {
        executor.shutdown();
    }

}
